package com.ruoyi.im.ws;

import com.fasterxml.jackson.databind.JsonNode;
import com.ruoyi.im.dao.MessageDAO;
import com.ruoyi.im.domain.Message;
import com.ruoyi.im.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class MessageHandler extends TextWebSocketHandler {
    @Autowired
    private MessageDAO messageDAO;


    private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public Map<String, WebSocketSession> getSessions() {
        return sessions;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String username =  session.getAttributes().get("username").toString();
        // 将当前用户的session放置到map中 ，后面会使用相应的session通信
        sessions.put(username, session);

    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage
            textMessage) throws Exception {
        String username =  session.getAttributes().get("username").toString();

        JsonNode jsonNode = JsonUtils.readTree(textMessage.getPayload());
        String toId = jsonNode.get("toId").toString();
        String msg = jsonNode.get("msg").asText();

        Message message = Message.builder()
                .from(username)
                .to(toId)
                .msg(msg)
                .build();

        // 将消息保存到MongoDB
        message = this.messageDAO.saveMessage(message);

        // 判断to用户是否在线
        WebSocketSession toSession = sessions.get(toId);
        if (toSession != null && toSession.isOpen()) {
            //TODO 具体格式需要和前端对接
            toSession.sendMessage(new
                    TextMessage(JsonUtils.serialize(message)));

            // 更新消息状态为已读
            this.messageDAO.updateMessageState(message.getBusinessId(), toId, 2);
        }
    }
}
